package com.mc.read.adminapi.manager;

import com.alibaba.fastjson.JSON;
import com.mc.read.common.MapConfig;
import com.mc.read.common.emun.ServiceCodeEnum;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.common.util.Md5Util;
import com.mc.read.dao.mapper.sys.SyspermissionMapper;
import com.mc.read.dao.mapper.sys.SysuserMapper;
import com.mc.read.dao.models.sys.Sysuser;
import com.mc.read.vo.request.BaseRequest;
import com.mc.read.vo.respose.BaseRespose;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Set;

/**
 * @author liuhao
 * @date 2019/6/13 11:43
 */
@Component
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
public class LoginManager {
    @Autowired
    SysuserMapper sysuserMapper;
    @Autowired
    SyspermissionMapper syspermissionMapper;

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 员工登录 userLogin
     **/
    public BaseRespose userLogin(BaseRequest baseRequest) {
        BaseRespose baseRespose = new BaseRespose();
        Sysuser sysuser = null;
        try {
            sysuser = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Sysuser.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL);
        }
        if (ObjectUtils.isEmpty(sysuser.getLoginname()) || ObjectUtils.isEmpty(sysuser.getPassword())) {
            throw new ServiceException(203020, "账号或密码不能为空", JSON.toJSONString(baseRequest));
        }
        Sysuser sysuserinfo = sysuserMapper.selectByLoginName(sysuser.getLoginname());
        if (ObjectUtils.isEmpty(sysuserinfo)) {
            throw new ServiceException(203020, "未找到该员工", JSON.toJSONString(baseRequest));
        }
        if (!Md5Util.psdMd5(sysuser.getPassword(), sysuser.getLoginname()).equals(sysuserinfo.getPassword())) {
            throw new ServiceException(203020, "密码错误", JSON.toJSONString(baseRequest));
        }
        if (sysuserinfo.getState() == 1) {
            throw new ServiceException(203020, "该用户已被禁用");
        }
        //信息放入map缓存
        Sysuser sysuser1=sysuserinfo;
        MapConfig.userMap.put(sysuserinfo.getUserid(), sysuser1);
        //是普通员工
        if (sysuserinfo.getUsertype() == 1) {
            Set<String> perset = syspermissionMapper.selectUserPer(sysuserinfo.getUserid());
            MapConfig.userPerMap.put(sysuserinfo.getUserid(), perset);
        }
        sysuserinfo.setPassword(null);
        baseRespose.setReturnString(sysuserinfo);

        return baseRespose;
    }
}
